package com.taptech.doufu.weex;

import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.ui.activity.MainHomeActivity;
import com.taptech.doufu.util.FileUtil2;
import com.taptech.doufu.util.PackageUtils;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.taptech.doufu.util.zip.ZipUtils;
import com.taptech.doufu.weex.http.TFHttpError;
import com.taptech.doufu.weex.http.TFHttpResponse;
import com.taptech.doufu.weex.http.TFHttpUtil;

import java.util.HashMap;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by qlx on 2016/12/16.
 * 热更新工具 for weex
 */

public class TFHotUpdateUtil {

    private static boolean isDownloading = false;// 是否在下载中
    private static long lastChackPartWeexTime = 0;
    private static long PART_WEEX_CHECK_DURATION = 10*60*1000; //10分钟内只能请求一次，防止请求次数太多


    /**
     * 检查部分资源是否更新
     */
    public static void checkPartWeexSource() {
        long currTime = System.currentTimeMillis();
        //如果正在下载全量资源包则不下载增量包
        if (isDownloading)
            return;
        //某个时间段内只能请求一次，
        if (currTime - lastChackPartWeexTime < PART_WEEX_CHECK_DURATION) {
            return;
        }
        lastChackPartWeexTime = currTime;
        String url = "version/douhua_part_weex";
        HashMap param = new HashMap();
        String version = getPartVersion();
        param.put("version", version);
        TFHttpUtil.requestGet(url, param, new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                if ((error == null)){
                    try {
                        if (json.getInteger("status") == 0){
                            boolean needUpdate = json.getJSONObject("data").getBoolean("latest");
                            //是否需要刷新首页的'社区'、'消息'、'个人中心'
                            boolean needRefreshPC = false;
                            boolean needRefreshMessage= false;
                            boolean needRefreshFind = false;
                            if (json.getJSONObject("data").containsKey("special_page")){
                                JSONObject specialPage = json.getJSONObject("data").getJSONObject("special_page");
                                if (specialPage != null) {
                                    if (specialPage.containsKey("need_refresh_PC")) {
                                        needRefreshPC = specialPage.getBoolean("need_refresh_PC");
                                    }

                                    if (specialPage.containsKey("need_refresh_message")) {
                                        needRefreshMessage = specialPage.getBoolean("need_refresh_message");
                                    }

                                    if (specialPage.containsKey("need_refresh_find")) {
                                        needRefreshFind = specialPage.getBoolean("need_refresh_find");
                                    }

                                }
                            }
                            if (needUpdate){
                                String version = json.getJSONObject("data").getString("version");
                                String downUrl = json.getJSONObject("data").getString("downloadUrl");
                                downloadPartFile(downUrl, version,needRefreshPC,needRefreshMessage,needRefreshFind);
                            }
                            //刷新时长可由服务器控制
                            if (json.getJSONObject("data").containsKey("check_duration")) {
                                long duration = json.getJSONObject("data").getLong("check_duration");
                                if (duration > 0) {
                                    PART_WEEX_CHECK_DURATION = duration;
                                }
                            }

                        }
                    }catch (Exception e){

                    }
                }
            }
        });
    }





    private static String getPartVersion() {
        return DiaoBaoSharedPreferences.getSharedPreferencesValueToString("TFPartWeexVersion_"+PackageUtils.versionName, WeMediaApplication.applicationContext, "0");
    }


    private static void setPartVersion(String version) {
        DiaoBaoSharedPreferences.setSharedPreferencesValueToString("TFPartWeexVersion_"+PackageUtils.versionName,version,WeMediaApplication.applicationContext);
    }




    private static void  downloadPartFile(String url , final String version, final boolean needRefreshPC, final boolean needRefreshMessage, final boolean needRefreshFind){
        final  String downDir =  TFWXUtil.wxBaseCacheDir();
        String path = TFWXUtil.wxBaseCacheDir() + "/weex.zip";
        FileUtil2.deleteAllWithPath(path);
        TFHttpUtil.downLoadFile(url, path, new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                try {
                    String path = json.getString("destFilePath");
                    ZipUtils.UnZipFolder(path,downDir);
                    setPartVersion(version);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                }
            }
        });
    }


    private static String SP_KEY_LOCAL_WEEX_ZIP = "UnZipLocalWeex_10_10_0_2" + PackageUtils.getVersionCode(WeMediaApplication.applicationContext);

    public static void upZipLocalWeex() {

        boolean canUnZip = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SP_KEY_LOCAL_WEEX_ZIP, WeMediaApplication.applicationContext, true);
        if (canUnZip){
            Observable.create((Observable.OnSubscribe<String>) subscriber -> {
                try {
                    String downDir =  TFWXUtil.wxBaseCacheDir();
                    ZipUtils.UnZipFolderFromAsset(WeMediaApplication.applicationContext,"weex.zip",downDir);
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SP_KEY_LOCAL_WEEX_ZIP,false,WeMediaApplication.applicationContext);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    subscriber.onNext("");
                }
            })
                    .compose(RxJavaHelper.<String>observeOnMainThread())
                    .subscribe(new BaseSubscriber<String>(){
                        @Override
                        public void onNext(String o) {
                            super.onNext(o);
//                            checkPartWeexSource();
                        }
                    });
        }else{
//            checkPartWeexSource();
        }
    }


}
